#!/usr/bin/env bash

alias gets='get_snippets'
function update_complete_for_snippets() {
  complete -W "$(cd ${snippets_dir}; find . -type f | sed 's@^./@@' | xargs)" gets sets dels edits tpl stpl sst srd srt srs
}
update_complete_for_snippets
function get_snippets() {
  local _list _matched_file _is_only_one_matched
  if [ -z "${1+x}" ]
  then
    _list=$(find ${snippets_dir} ! -path ${snippets_dir} -printf '%y %P\n' | sort -k '2')
    echo "$_list"
    update_complete_for_snippets
  else
    if [[ ! -f ${snippets_dir}/$1 ]]; then
      _matched_file="$(realpath $(find ${snippets_dir} \( -type f -o -type l \) -a -name *$1*) 2>/dev/null | xargs -n1 | uniq)"
      _is_only_one_matched="$(echo "$_matched_file" | sed '/^$/d' | wc -l)"
      if [[ $_is_only_one_matched -eq 1 ]]; then
        cat $_matched_file
      else
        _list=$(find ${snippets_dir} ! -path ${snippets_dir} -printf '%y %P\n' | sort -k '2')
        echo "$_list" | less --pattern="$1"
        return 2
      fi
    else
      cat ${snippets_dir}/$1
    fi
  fi
}

alias edits='edit_snippets'
function edit_snippets() {
  mktouch "${snippets_dir}/$1"
  eval "vim -u ${shell_dir}/.vimrc -c set\ filetype=sh ${snippets_dir}/$1"
  update_complete_for_snippets
}
alias sets='set_snippets'
function set_snippets() {
  mktouch "${snippets_dir}/$1"
  echo "${@:2}" > ${snippets_dir}/$1
  update_complete_for_snippets
}
alias setsd='set_snippets_heredoc'
function set_snippets_heredoc() {
  mktouch "${snippets_dir}/$1"
  read -d ' ' heredoc
  eval "echo $heredoc > ${snippets_dir}/$1"
  update_complete_for_snippets
}
alias dels='delete_snippets'
function delete_snippets() {
  if [[ $# -eq 0 ]]; then
    find ${shell_dir} -type l ! -exec test -e {} \; -ok \rm {} \;
  else
    \rm ${snippets_dir}/$1
  fi
  update_complete_for_snippets
}
